package com.alibaba.citrus.ots.sales.plan.facade.service.setting;

import com.alibaba.citrus.ots.common.annotation.FacadeInvoker;
import com.alibaba.citrus.ots.common.model.ImportRequest;
import com.alibaba.citrus.ots.sales.plan.api.setting.SalesPlanScItemFileService;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.SalesPlanScItemImportRequest;
import com.alibaba.citrus.ots.sales.plan.facade.service.SalesPlanOutCommonService;
import com.alibaba.cz.base.tool.message.ErrorMessage;
import com.alibaba.cz.base.tool.result.Result;
import com.epoch.app.bcots.model.dto.CategorySDO;
import com.epoch.app.bcots.model.dto.QueryCategoryInfoByIdsRequest;
import com.epoch.app.bcots.model.dto.ScItemSDO;
import com.epoch.app.bcots.sales_plan.salesplanscitem.dto.BatchCreateSalesPlanScItemRequest;
import com.epoch.app.bcots.sales_plan.salesplanscitem.dto.BatchCreateSalesPlanScItemResponse;
import com.epoch.app.bcots.sales_plan.salesplanscitem.dto.SalesPlanScItemLoadListRequest;
import com.epoch.app.bcots.sales_plan.salesplanscitem.model.SalesPlanScItem;
import com.epoch.app.bcots.sales_plan.salesplanscitem.service.SalesPlanScItemService;
import com.epoch.app.bcots.service.BaseDataService;
import com.epoch.app.otsplatformenhance.enums.OrganizationTypeEnum;
import com.epoch.app.otsplatformenhance.model.dto.GetTopOrganizationListRequest;
import com.epoch.app.otsplatformenhance.model.dto.TopOrganizationListResponse;
import com.epoch.app.otsplatformenhance.sdo.OrganizationSDO;
import com.epoch.app.otsplatformenhance.service.OtsPlatformEnhanceService;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wangyibing
 */
@Component
public class SalesPlanScItemFileServiceImpl implements SalesPlanScItemFileService {
    @Resource
    private SalesPlanOutCommonService salesPlanOutCommonService;

    @Resource
    private SalesPlanScItemService salesPlanScItemService;

    @Resource
    private BaseDataService baseDataService;

    @Resource
    private OtsPlatformEnhanceService otsPlatformEnhanceService;

    @Override
    @FacadeInvoker
    public Result<List<SalesPlanScItemImportRequest>> salesPlanScItemImport(List<SalesPlanScItemImportRequest> requestList, String orgBussinessUnitCode) {
        if (CollectionUtils.isEmpty(requestList)) {
            return Result.success(Lists.newArrayList());
        }
        //orgBusinessUnitCode为空说明登录人不是调度员
        if (Strings.isBlank(orgBussinessUnitCode)) {
            return Result.failure(ImportRequest.setRequestErrorMessage(requestList, ErrorMessage.code("OTS-01-003-01-15-015", null).getDisplayErrorMessage()),"OTS-01-003-01-15-015", ErrorMessage.code("OTS-01-003-01-15-015", null).getDisplayErrorMessage());
        }
        //进一步判断员工的业务单元是否存在
        com.alibaba.lattice2.epoch.sdk.model.Result<List<TopOrganizationListResponse>> organization = otsPlatformEnhanceService.getTopOrganizationList(GetTopOrganizationListRequest.builder()
                .id(orgBussinessUnitCode).type(OrganizationTypeEnum.COMPANY.getCode()).build());
        if (!organization.isSuccess() || CollectionUtils.isEmpty(organization.getResult())) {
            return Result.failure(ImportRequest.setRequestErrorMessage(requestList, ErrorMessage.code("OTS-01-003-01-15-020", null).getDisplayErrorMessage()), "OTS-01-003-01-15-020", ErrorMessage.code("OTS-01-003-01-15-020", null).getDisplayErrorMessage());
        }
        Optional<String> orgBussinessUnitOutCode = organization.getResult().stream().findFirst().map(TopOrganizationListResponse::getCode);

        Set<String> businessCodes = requestList.stream().map(SalesPlanScItemImportRequest::getOrgBusinessUnitCode).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        Set<String> orgSalesOrganizationCodes = requestList.stream().map(SalesPlanScItemImportRequest::getOrgSalesOrganizationCode).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        Set<String> salesChannelCodes = requestList.stream().map(SalesPlanScItemImportRequest::getOrgSalesChannelCode).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        Set<String> scItemIds = requestList.stream().map(it -> {
            String scItemId = it.getScItemId();
            if (StringUtils.isNotBlank(scItemId)) {
                return scItemId.trim();
            } else {
                return scItemId;
            }
        }).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        Set<String> codes = Sets.newHashSet();
        codes.addAll(businessCodes);
        codes.addAll(orgSalesOrganizationCodes);
        codes.addAll(salesChannelCodes);
        Map<String, com.epoch.app.otsplatformenhance.sdo.OrganizationSDO> organizationMapByOutCode = salesPlanOutCommonService.getOrganizationMapByOutCode(codes);
        //所有组织都映射不上，不存在
        if (Objects.isNull(organizationMapByOutCode)) {
            return Result.success(ImportRequest.setRequestErrorMessage(requestList, ErrorMessage.code("OTS-01-003-01-16-003", null).getDisplayErrorMessage()));
        }
        //所有货品都找不到
        Map<String, ScItemSDO> scItemMapByIds = salesPlanOutCommonService.getScItemMapByOutId(scItemIds);
        if (Objects.isNull(scItemMapByIds)) {
            return Result.success(ImportRequest.setRequestErrorMessage(requestList, ErrorMessage.code("OTS-01-005-02-15-001", null).getDisplayErrorMessage()));
        }

        List<SalesPlanScItem> addRequest = Lists.newArrayList();
        List<SalesPlanScItem> updateRequest = Lists.newArrayList();
        for (SalesPlanScItemImportRequest salesPlanScItemImportRequest : requestList) {
            //判空
            if (StringUtils.isBlank(salesPlanScItemImportRequest.getOrgBusinessUnitCode())) {
                salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-005-02-15-009", null).getDisplayErrorMessage()));
                continue;
            }
            if (StringUtils.isBlank(salesPlanScItemImportRequest.getOrgSalesOrganizationCode())) {
                salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-005-02-15-010", null).getDisplayErrorMessage()));
                continue;
            }
            if (StringUtils.isBlank(salesPlanScItemImportRequest.getOrgSalesChannelCode())) {
                salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-005-02-15-011", null).getDisplayErrorMessage()));
                continue;
            }
            if (StringUtils.isBlank(salesPlanScItemImportRequest.getScItemId())) {
                salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-005-02-15-003", null).getDisplayErrorMessage()));
                continue;
            }
            //判断常规销售价是否小于0
            if (Objects.nonNull(salesPlanScItemImportRequest.getCostInsuranceFreight()) && salesPlanScItemImportRequest.getCostInsuranceFreight() < 0) {
                salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-005-02-15-004", null).getDisplayErrorMessage()));
                continue;
            }
            //判断到岸价是否小于0
            if (Objects.nonNull(salesPlanScItemImportRequest.getOutboundPrice()) && salesPlanScItemImportRequest.getOutboundPrice() < 0) {
                salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-005-02-15-008", null).getDisplayErrorMessage()));
                continue;
            }

            //判断导入文件填写的业务单元是否存在
            if (organizationMapByOutCode.get(salesPlanScItemImportRequest.getOrgBusinessUnitCode()) == null || !organizationMapByOutCode.get(salesPlanScItemImportRequest.getOrgBusinessUnitCode()).getType().equals(OrganizationTypeEnum.COMPANY.getCode())) {
                salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-003-01-15-011", null).getDisplayErrorMessage()));
                continue;
            }
            //判断用户所属业务单元和导入文件中填写的业务单元是否匹配
            if (!salesPlanScItemImportRequest.getOrgBusinessUnitCode().equals(orgBussinessUnitOutCode.get())) {
                salesPlanScItemImportRequest.setErrorMessage(ErrorMessage.code("OTS-01-003-01-15-016", null).getDisplayErrorMessage());
                continue;
            }
            //判断销售组织是否存在
            if (organizationMapByOutCode.get(salesPlanScItemImportRequest.getOrgSalesOrganizationCode()) == null || !organizationMapByOutCode.get(salesPlanScItemImportRequest.getOrgSalesOrganizationCode()).getType().equals(OrganizationTypeEnum.SALES_ORGANIZATION.getCode())) {
                salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-003-01-15-012", null).getDisplayErrorMessage()));
                continue;
            }
            OrganizationSDO businessSDO = organizationMapByOutCode.get(salesPlanScItemImportRequest.getOrgBusinessUnitCode());
            //校验销售组织是否和业务单元匹配
            OrganizationSDO organizationSDO = organizationMapByOutCode.get(salesPlanScItemImportRequest.getOrgSalesOrganizationCode());
            if (!organizationSDO.getParentId().equals(businessSDO.getId())) {
                salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-003-01-15-013", null).getDisplayErrorMessage()));
                continue;
            }

            //判断销售渠道是否存在
            if (organizationMapByOutCode.get(salesPlanScItemImportRequest.getOrgSalesChannelCode()) == null || !organizationMapByOutCode.get(salesPlanScItemImportRequest.getOrgSalesChannelCode()).getType().equals(OrganizationTypeEnum.SALES_CHANNEL.getCode())) {
                salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-003-01-15-013", null).getDisplayErrorMessage()));
                continue;
            }
            //校验销售组织是否和销售渠道匹配
            OrganizationSDO channelSDO = organizationMapByOutCode.get(salesPlanScItemImportRequest.getOrgSalesChannelCode());
            if (!channelSDO.getParentId().equals(organizationSDO.getId())) {
                salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-003-01-15-018", null).getDisplayErrorMessage()));
                continue;
            }
            if (scItemMapByIds.get(salesPlanScItemImportRequest.getScItemId()) == null) {
                salesPlanScItemImportRequest.setErrorMessage((ErrorMessage.code("OTS-01-005-02-15-001", null).getDisplayErrorMessage()));
                continue;
            }
//            //判断级联关系
//            String id = organizationSDOMap.get(Optional.ofNullable(salesPlanScItemImportRequest.getOrgSalesChannelCode())).getId();
//            com.alibaba.lattice2.epoch.sdk.model.Result<List<TopOrganizationListResponse>> organizationResult = otsPlatformEnhanceService.getTopOrganizationList(GetTopOrganizationListRequest.builder()
//                    .id(id).type(103).build());
//            if (!organizationResult.isSuccess() || CollectionUtils.isEmpty(organizationResult.getResult())) {
//                salesPlanScItemImportRequest.setErrorMessage(ErrorMessage.code("OTS-01-003-01-15-017", null).getDisplayErrorMessage());
//                continue;
//            }
//            Map<String, Integer> organizationMap = organizationResult.getResult().stream().collect(Collectors.toMap(TopOrganizationListResponse::getCode, TopOrganizationListResponse::getType));
//            if (organizationMap.get(salesPlanScItemImportRequest.getOrgSalesOrganizationCode()) == null || !organizationMap.get(salesPlanScItemImportRequest.getOrgSalesOrganizationCode()).equals(OrganizationTypeEnum.SALES_ORGANIZATION.getCode())) {
//                salesPlanScItemImportRequest.setErrorMessage(ErrorMessage.code("OTS-01-003-01-15-018", null).getDisplayErrorMessage());
//                continue;
//            } else {
//                if (organizationMap.get(salesPlanScItemImportRequest.getOrgBusinessUnitCode()) == null || !organizationMap.get(salesPlanScItemImportRequest.getOrgBusinessUnitCode()).equals(OrganizationTypeEnum.COMPANY.getCode())) {
//                    salesPlanScItemImportRequest.setErrorMessage(ErrorMessage.code("OTS-01-003-01-15-019", null).getDisplayErrorMessage());
//                    continue;
//                }
//            }

            //判断平台是否存在这条数据
            SalesPlanScItemLoadListRequest scItemLoadListRequest = SalesPlanScItemLoadListRequest.newSalesPlanScItemLoadListRequestBuilder().build();
            scItemLoadListRequest.setOrgBusinessUnitCode(organizationMapByOutCode.get(salesPlanScItemImportRequest.getOrgBusinessUnitCode()).getId());
            scItemLoadListRequest.setOrgSalesOrganizationCode(organizationMapByOutCode.get(salesPlanScItemImportRequest.getOrgSalesOrganizationCode()).getId());
            scItemLoadListRequest.setOrgSalesChannelCode(organizationMapByOutCode.get(salesPlanScItemImportRequest.getOrgSalesChannelCode()).getId());
            scItemLoadListRequest.setScItemId(scItemMapByIds.get(salesPlanScItemImportRequest.getScItemId()).getScItemId());
            com.alibaba.lattice2.epoch.sdk.model.Result<List<SalesPlanScItem>> salesPlanScItemList = salesPlanScItemService.loadSalesPlanScItemList(scItemLoadListRequest);
            SalesPlanScItem salesPlanScItem = new SalesPlanScItem();
            salesPlanScItem.setScItemId(scItemMapByIds.get(salesPlanScItemImportRequest.getScItemId()).getScItemId());
            //类目
            String leafCategoryId = scItemMapByIds.get(salesPlanScItemImportRequest.getScItemId()).getLeafCategoryId();
            if (StringUtils.isNotEmpty(leafCategoryId)) {
                QueryCategoryInfoByIdsRequest build = QueryCategoryInfoByIdsRequest.builder().categoryIdList(Lists.newArrayList(leafCategoryId)).build();
                com.alibaba.lattice2.epoch.sdk.model.Result<List<CategorySDO>> listResult = baseDataService.queryCategoryInfoByIds(build);
                if (listResult != null || listResult.isSuccess() || listResult.getResult() != null) {
                    CategorySDO categorySDO = listResult.getResult().stream().findFirst().get();
                    if (categorySDO.getRoot()) {
                        //该类目是根节点
                        salesPlanScItem.setScItemRootCategoryId(categorySDO.getRootCategoryId());
                    } else {
                        //叶子节点
                        salesPlanScItem.setScItemLeafCategoryId(categorySDO.getCategoryId());
                        salesPlanScItem.setScItemRootCategoryId(categorySDO.getRootCategoryId());
                    }
                }
            }
            salesPlanScItem.setOrgBusinessUnitCode(organizationMapByOutCode.get(salesPlanScItemImportRequest.getOrgBusinessUnitCode()).getId());
            salesPlanScItem.setOrgSalesOrganizationCode(organizationMapByOutCode.get(salesPlanScItemImportRequest.getOrgSalesOrganizationCode()).getId());
            salesPlanScItem.setOrgSalesChannelCode(organizationMapByOutCode.get(salesPlanScItemImportRequest.getOrgSalesChannelCode()).getId());
            if (Objects.nonNull(salesPlanScItemImportRequest.getCostInsuranceFreight())) {
                salesPlanScItem.setCostInsuranceFreight(doubleToLong(salesPlanScItemImportRequest.getCostInsuranceFreight()));
            }
            if (Objects.nonNull(salesPlanScItemImportRequest.getOutboundPrice())) {
                salesPlanScItem.setOutboundPrice(doubleToLong(salesPlanScItemImportRequest.getOutboundPrice()));
            }
            //状态
            salesPlanScItem.setMark(salesPlanScItemImportRequest.getMark());
            if (Objects.isNull(salesPlanScItemImportRequest.getStatus())) {
                salesPlanScItem.setStatus(1);
            } else {
                salesPlanScItem.setStatus(salesPlanScItemImportRequest.getStatus());
            }

            if (salesPlanScItemList == null || CollectionUtils.isEmpty(salesPlanScItemList.getResult())) {
//                salesPlanScItem.setGmtCreate(new Date());
//                salesPlanScItem.setGmtModified(new Date());
                salesPlanScItem.setGmt_create(new Date());
                salesPlanScItem.setGmt_modified(new Date());
                addRequest.add(salesPlanScItem);
            } else {
                SalesPlanScItem item = salesPlanScItemList.getResult().stream().findFirst().get();
                salesPlanScItem.setStatus(1);
                salesPlanScItem.setId(item.getId());
//                salesPlanScItem.setGmtModified(new Date());
                salesPlanScItem.setGmt_modified(new Date());
                salesPlanScItemService.updateSalesPlanScItem(salesPlanScItem);
                updateRequest.add(salesPlanScItem);
            }
        }
        if (CollectionUtils.isNotEmpty(addRequest)) {
            //批量新增和批量更新
            BatchCreateSalesPlanScItemRequest salesPlanScItemRequest = new BatchCreateSalesPlanScItemRequest();
            salesPlanScItemRequest.setRequestList(addRequest);
            BatchCreateSalesPlanScItemResponse batchCreateSalesPlanScItemResponse = salesPlanScItemService.batchCreateSalesPlanScItem(salesPlanScItemRequest);
        }

        return Result.success(requestList);
    }

    private Long doubleToLong(Double d) {
        if (d == null) {
            return null;
        }
        return (long) (d * 100);
    }
}
